package cc.lucien.controller;

import cc.lucien.entity.Order;
import cc.lucien.entity.OrderVO;
import cc.lucien.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/show")
    @ResponseBody
    public OrderVO show() {
        OrderVO orderVO = new OrderVO();
        orderVO.setCode(0);
        orderVO.setMsg("");
        orderVO.setCount(1L);
        orderVO.setData(orderService.findAll());
        return orderVO;
    }

    @PostMapping("/save")
    public String save(Order order) {
        /*
        先查询一下是否已经有与该公司的合作记录，如果有就在此基础上累加
        否则新建一条记录
         */
        Order old = orderService.findByCompanyName(order.getCompanyName());
        if (old == null) {
            orderService.save(order);
        } else {
            old.setOrderCount(old.getOrderCount()+1);
            old.setSumMoney(old.getSumMoney() + order.getSumMoney());
            orderService.update(old);
        }
        return "orderTable";
    }

    @GetMapping("/toUpdate/{id}")
    public ModelAndView toUpdate(@PathVariable("id") Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("orderUpdate");
        modelAndView.addObject("order", orderService.findById(id));
        return modelAndView;
    }

    @PostMapping("/update")
    public String update(Order order) {
        orderService.update(order);
        return "orderTable";
    }
}
